package com.niji.littly_donkey_android.common;

import com.android.volley.*;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangshihui on 2015/11/30.
 * 上传文件
 * url：.....
  method：post
  参数：file
  接口给的参数：file 就是表单的key，传给mFilePartName;
  这是个测试类，测试上传头像没有问题，适合只上传单个文件的场景
 */
public class MultipartRequest extends Request<JSONObject> {
  private String mHeader;
  private Map<String, String> mMap;
  private String cookieFromResp = "";
  private Map<String, String> headerMap = new HashMap<>();
  private MultipartEntity entity = new MultipartEntity();
  private final Response.Listener<JSONObject> mListener;
  private final File mFilePart;
  private String mFilePartName;

  /**
   * @param url
   * @param listener
   * @param errorListener
   * @param file_name
   * @param file
   */
  public MultipartRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String file_name,File file)
  {
    super(Method.POST, url, errorListener);
    mListener = listener;
    mFilePart = file;
    mFilePartName=file_name;
    buildMultipartEntity();
  }

  /**
   * 添加文件参数
   */
  private void buildMultipartEntity()
  {
    entity.addPart(mFilePartName, new FileBody(mFilePart));
  }

  @Override
  public String getBodyContentType()
  {
    return entity.getContentType().getValue();
  }

  @Override
  public byte[] getBody() throws AuthFailureError
  {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
      entity.writeTo(bos);
    }
    catch (IOException e)
    {
      VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
  }

  /**
   * @param response
   * @return
   */
  @Override
  protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
  {
    try {
    JSONObject jsonObject;
    System.out.println(response.headers.toString());
    if (response.data.length != 0) {
      String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
      jsonObject = new JSONObject(jsonString);
    } else {
      jsonObject = new JSONObject();
    }
    //获取数据头
    mHeader = response.headers.toString();
    //提取Cookie(JSESSIONID)
    Pattern pattern = Pattern.compile("Set-Cookie=.*?;");
    Matcher matcher = pattern.matcher(mHeader);
    if (matcher.find()) {
      cookieFromResp = matcher.group();
      cookieFromResp = cookieFromResp.substring(11, cookieFromResp.length() - 1);
      System.out.println("Cookie: " + cookieFromResp);
    }
    jsonObject.put("Cookie", cookieFromResp);
    return Response.success(jsonObject,
        HttpHeaderParser.parseCacheHeaders(response));
  } catch (UnsupportedEncodingException e) {
    return Response.error(new ParseError(e));
  } catch (JSONException je) {
    return Response.error(new ParseError(je));
  }
  }

  /**
   * @param response
   */
  @Override
  protected void deliverResponse(JSONObject response)
  {
    mListener.onResponse(response);
  }

  @Override
  protected Map<String, String> getParams() throws AuthFailureError {
    return mMap;
  }

  /**
   * @return
   * @throws AuthFailureError
   */
  @Override
  public Map<String, String> getHeaders() throws AuthFailureError {
    return headerMap;
  }

  /**
   * @return
   */
  @Override
  public RetryPolicy getRetryPolicy() {
    RetryPolicy retryPolicy = new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    return retryPolicy;
  }

  /**
   * @param cookie
   */
  //将Cookie加入数据头
  public void setSendCookie(String cookie) {
    headerMap.put("Cookie", cookie);
  }
}

